let fs = require('fs')
let sd = require('silly-datetime')
let path = require('path')
let dbPath = path.join(__dirname, '../data/msg.json')
let connection = require('../modules/connect')

exports.find = (callback) => {
    connection.query('select * from `msgs`', function(err, data) {
        if (err) { return callback(err) }
        return callback(null, data)
    })
}

exports.save = (info, callback) => {
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss')
    if (info.name == '' || info.name.length <= 0) {
        callback(null, 1)
    } else if (info.msg == '' || info.msg.length <= 0) {
        callback(null, 2)
    } else if (info.name.length < 2 || info.name.length > 10) {
        callback(null, 3)
    } else if (info.msg.length < 4 || info.msg.length > 100) {
        callback(null, 4)
    } else {
        connection.query('insert into `msgs` values(null,"' + info.name + '","' + info.msg + '","' + time + '");', function(err) {
            if (err) { return callback(err) }
            return callback(null, 0)
        })
    }
}

exports.findById = (id, callback) => {

    connection.query('select * from `msgs` where id=' + id + ';', function(err, data) {
        if (err) { return callback(err) }
        return callback(null, data);
    })
}


exports.updateById = function(info, callback) {
    if (info.name == '' || info.name.length <= 0) {
        return callback(null, 1)
    } else if (info.msg == '' || info.msg.length <= 0) {
        return callback(null, 2)
    } else if (info.name.length < 2 || info.name.length > 10) {
        return callback(null, 3)
    } else if (info.msg.length < 4 || info.msg.length > 100) {
        return callback(null, 4)
    } else {
        connection.query("update `msgs` set name='" + info.name + "',msg='" + info.msg + "' where id=" + info.id + ";", function(err) {
            if (err) { callback(err) }
            return callback(null)
        })
    }
}

exports.deleteById = function(id, callback) {
    connection.query('delete from `msgs` where id=' + id + ';', function(err) {
        if (err) { callback(err) }
        return callback(null)
    })
}
